package com.hyperf.core.util;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hyperf.core.exception.CustomException;
import com.hyperf.core.bean.result.PageResult;

import java.util.List;

/**
 * 分页工具类
 *
 * @author lizhaoyang
 */
public final class PageUtil {

    /**
     * 开启分页查询
     *
     * @param page     页码
     * @param pageSize 每页数量
     * @param <R>
     * @return
     */
    public static <R> Page<R> startPage(int page, int pageSize) {
        if (page <= 0 || pageSize <= 0) {
            throw new CustomException("page or pageSize cannot be less than or equal to 0");
        }
        return PageHelper.startPage(page, pageSize);
    }

    /**
     * 清空分页
     */
    public static void clearPage() {
        PageHelper.clearPage();
    }

    /**
     * 构建分页结果集
     *
     * @param page
     * @param <R>
     * @return
     */
    public static <R> PageResult<R> buildResult(Page<R> page) {
        return PageResult.buildResult(page.getPageNum(), page.getPageSize(), (int) page.getTotal(), page.getResult());
    }

    /**
     * 封装分页结果集
     *
     * @param page
     * @param data
     * @param <R>
     * @return
     */
    public static <R> PageResult<R> buildPageResult(Page<?> page, List<R> data) {
        return PageResult.buildResult(page.getPageNum(), page.getPageSize(), (int) page.getTotal(), data);
    }

    /**
     * 构建分页结果集
     *
     * @param pageInfo
     * @param <R>
     * @return
     */
    public static <R> PageResult<R> buildResult(PageInfo<R> pageInfo) {
        return PageResult.buildResult(pageInfo.getPageNum(), pageInfo.getPageSize(), (int) pageInfo.getTotal(), pageInfo.getList());
    }

    /**
     * 构建分页结果集
     *
     * @param pageInfo
     * @param data
     * @param <R>
     * @return
     */
    public static <R> PageResult<R> buildPageResult(PageInfo<?> pageInfo, List<R> data) {
        return PageResult.buildResult(pageInfo.getPageNum(), pageInfo.getPageSize(), (int) pageInfo.getTotal(), data);
    }

    /**
     * 构建分页结果集
     *
     * @param page
     * @param pageSize
     * @param <R>
     * @return
     */
    public static <R> PageResult<R> buildPageResult(int page, int pageSize) {
        return PageResult.buildResult(page, pageSize);
    }

    /**
     * 构建分页结果集
     *
     * @param page
     * @param pageSize
     * @param total
     * @param data
     * @param <R>
     * @return
     */
    public static <R> PageResult<R> buildPageResult(int page, int pageSize, int total, List<R> data) {
        return PageResult.buildResult(page, pageSize, total, data);
    }

    /**
     * 构建分页结果集
     *
     * @param pageResult
     * @param data
     * @param <R>
     * @return
     */
    public static <R> PageResult<R> buildPageResult(PageResult<?> pageResult, List<R> data) {
        return PageResult.buildResult(pageResult.getPage(), pageResult.getPageSize(), pageResult.getTotal(), data);
    }
}
